import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.Enumeration;

public class PublishSamole {
    // MQTT服务器地址
    private static final String BROKER = "tcp://localhost:1883";
    // 客户端ID
    private static final String PUBLISHER_ID = "java-publisher";
    // 主题
    private static final String TOPIC = "test/topic";

    public static void main(String[] args) {
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            // 创建客户端
            MqttClient client = new MqttClient(BROKER, PUBLISHER_ID, persistence);

            // 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);

            connOpts.setUserName("your_mqtt_username"); // 你的MQTT用户名
            connOpts.setPassword("your_mqtt_password".toCharArray()); // 密码需用char数组形式
            // 连接服务器
            System.out.println("连接到MQTT服务器: " + BROKER);
            client.connect(connOpts);
            System.out.println("连接成功");

            // 发布消息
            String content = "Hello, MQTT!";
            System.out.println("发布消息到主题: " + TOPIC + " 内容: " + content);

            MqttMessage message = new MqttMessage(content.getBytes());
            // QoS级别，0:最多一次，1:至少一次，2:恰好一次
            message.setQos(1);

            client.publish(TOPIC, message);
            System.out.println("消息发布成功");

            // 断开连接
            client.disconnect();
            System.out.println("已断开连接");

        } catch (MqttException me) {
            System.out.println("错误: " + me.getMessage());
            me.printStackTrace();
        }
    }
}